<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

// 返回json
function reJson($re){
    if(!is_string($re)){
        if($re){
            return json(['state'=> 0,'msg'=>'成功','data'=>$re]);
        }else {
            return json(['state' => 10001, 'msg' => '失败', 'data' => $re]);
        }
    }
    return json(['state'=> 10001,'msg'=>'失败','data'=>$re]);
}

//转义函数
function strcode($arr){
    foreach($arr as $v){
        addslashes($v);
    }
    return $arr;
}

//反转义
function strdecode($arr){
    foreach($arr as $v){
        stripslashes($v);
    }
    return $arr;
}

//curl连接
function httpReq($url){
    // 初始化
    $ch = curl_init($url);
    // 相关配置
    // 不要头信息
    curl_setopt($ch,CURLOPT_HEADER,0);
    // 不直接在页面中输出
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    // 不检查证书
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
    // 设置超时时间
    curl_setopt($ch,CURLOPT_TIMEOUT,60);
    // 执行
    $data = curl_exec($ch);
    // 关闭
    curl_close($ch);

    return $data;
}

//头像上传函数
function imgUpload($request,$oldfile=''){
    //$arr = [];
    if($request->file()){
        $file = $request->file('pic');
        $fileMove = $file->validate(['size'=>204800,'ext'=>'jpg,png,gif'])->move('./upload/userimg');
        if($fileMove){
            //有旧图片
            if(!empty($oldfile)){
                unlink(\think\facade\Env::get('root_path').'public/upload/userimg/'.$oldfile);
            }
            return ['sta'=>true,'data'=>$fileMove->getSaveName()];
        }else{
            return ['sta'=>false,'data'=>$fileMove->getError()];
        }
    }
}

// 无限极分类
function tree($arr,$pid = 0,$ver = 0){
    //static $data = [];
    foreach ($arr as $v){
        if($pid == $v['pid']){
            $v['ver'] = $ver;
            //$date[] = $v;
            tree($arr,$v['id'],$ver+1);
        }
    }
    return $arr;
}

//分页查询函数
function pageque($obj,$arr=[],$where=[]){
    $offset = $arr['offset'] ?? 0;
    $limit = $arr['limit'] ?? config('api.limit');
    //限制最大条数
    $limit = min(config('api.maxlist'),$limit);
    //查询
    return strdecode($obj::where($where)->limit($offset,$limit)->selectOrFail());
}

